<template>
    <div class="container">
        <!-- 导航栏区域开始 -->
        <TridentNavBar>
            <template #left><i class="iconfont icon-zuojiantou"></i></template>
            <template #default>聊天记录better-scroll版</template>
        </TridentNavBar>
        <!-- 导航栏区域结束 -->

        <!-- 过滤区域开始 -->
        <div class="filter-wrap">
            <van-dropdown-menu active-color="#27BA9B">
                <van-dropdown-item @change="handleFilterMessage" v-model="messageListParams.type" :options="messagetypes" />
                <van-dropdown-item @change="handleSortMessage" v-model="messageListParams.sort_type" :options="sortTypes" />
                <van-dropdown-item title="日期筛选">
                    <van-cell-group inset>
                        <van-field
                            v-model="messageListParams.start_create_time"
                            label="开始日期"
                            left-icon="notes-o"
                            placeholder="日期格式:0000-00-00"
                        />
                        <van-field
                            v-model="messageListParams.end_create_time"
                            clearable
                            label="结束日期"
                            left-icon="notes-o"
                            placeholder="日期格式:0000-00-00"
                        />
                    </van-cell-group>

                    <div class="date-filter-btn-box">
                        <van-button style="margin-right: 15px;" color="#bbb" type="primary" @click="onReset">
                            重 置
                        </van-button>

                        <van-button color="#27BA9B" type="primary" @click="onConfirm">
                            确 认
                        </van-button>
                    </div>
                </van-dropdown-item>
            </van-dropdown-menu>
        </div>
        <!-- 过滤区域结束 -->


        <!-- 列表区域开始 -->
        <!-- :style="domHeight > messageListHeight ? 'height: '+(domHeight-18)+'px;': ''" -->
         <div class="content-wrap">
            <div class="list-wrap">
                <div class="">
                    <div class="record-item" v-for="(item, index) in messageList" :key="index">
                        <div class="title-box">
                            <van-image
                                round
                                width="30"
                                height="30"
                                fit="cover"
                                :src="item.from_user?.avatar_url ? global.MINIO_FILE_DOMAIN + item.from_user?.avatar_url : 'src/assets/images/default_avatar.png'"
                            />
                            <div class="username">{{ item.from_user?.username }}</div>
                        </div>
                        <div class="content">
                            <div class="text" v-if="item.type == 1">{{ item.contents }}</div>
                            <div class="image" v-else-if="item.type == 2">
                                <van-image
                                    width="80"
                                    height="80"
                                    fit="contain"
                                    :src="global.MINIO_FILE_DOMAIN + item.image_url"
                                    @click="handleShowImagePreview(global.MINIO_FILE_DOMAIN + item.image_url)"
                                />
                            </div>
                        </div>
                        <div class="time">{{ item.create_time }}</div>
                    </div>
                </div>
            </div>
         </div>
        <!-- 列表区域结束 -->
    </div>
</template>

<script lang="ts" setup>
import { reqMessageListAPI } from '@/apis/message'
import { useUserStore } from '@/store/modules/user'
import type { Message, MessageListParam } from '@/types/chat'
import BScroll from 'better-scroll'
import { showImagePreview } from 'vant'
import { inject, nextTick, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'


// 全局属性
const global: any = inject('global')

// 路由
const route = useRoute()

// 用户存储
const userStore = useUserStore()

const bscroll: any = ref(null)

onMounted(async () => {
    await getMessageList()
    bscroll.value = new BScroll((document.querySelector('.list-wrap')) as any, {
        scrollY: true,
        probeType: 3,
        click: true,
        pullUpLoad:true,
        pullDownRefresh: true, //开启下拉刷新
    })

    // 监听下拉刷新
    bscroll.value.on("pullingDown", pullingDownHandler);

    // 监听上拉加载
    bscroll.value.on('pullingUp', pullingUpHandler)
})



// ---------------- 处理日期筛选功能开始 ----------------
const onReset = () => {}
const onConfirm = () => {}
// ---------------- 处理日期筛选功能结束 ----------------



// ------------------ 处理筛选功能开始 ------------------
// 消息类型
const messagetypes = ref([
    {
        text: '全部',
        value: 0
    },
    {
        text: '文本',
        value: 1
    },
    {
        text: '图片',
        value: 2
    },
    {
        text: '语音',
        value: 3
    },
    {
        text: '视频',
        value: 4
    },
    {
        text: '位置',
        value: 5
    }
])

// 排序类型
const sortTypes = ref([
    {
        text: '时间倒序',
        value: 'desc'
    },
    {
        text: '时间升序',
        value: 'asc'
    }
])

// 过滤消息类型
const handleFilterMessage = async (value: any) => {
    messageList.value = []
    messageListParams.page = 1
    messageListParams.type = value
    // 当加载完成设置为false,将会自动调用getMessageList()方法获取数据,不需要手动调用
    // 切记
    finished.value = false

    await onLoadMore()

    // 置顶
    // window.scrollTo(0,0)
    // if (messageListParams.page == 1) {
    //     await getMessageList()
    // } else {
    //     finished.value = false
    // }
}

// 消息排序
const handleSortMessage = async (value: any) => {
    messageList.value = []
    messageListParams.page = 1
    messageListParams.sort_type = value

    // 当加载完成设置为false,将会自动调用getMessageList()方法获取数据,不需要手动调用
    // 切记
    finished.value = false

    // await getMessageList()

    // 置顶
    window.scrollTo(0,0)
}
// ----------------- 处理筛选功能结束 ------------------



// ----------------- 下拉刷新功能开始 -----------------
const pullingDownHandler = async () => {
    finished.value = false
    messageListParams.page = 1
    messageList.value = []
    await getMessageList()
    bscroll.value.finishPullDown()
    bscroll.value.refresh()
}
// ----------------- 下拉刷新功能结束 -----------------



// --------------- 上拉加载更多功能开始 ---------------
const pullingUpHandler = async () => {
    await getMessageList()
    bscroll.value.finishPullUp()
    bscroll.value.refresh()
}
// --------------- 上拉加载更多功能结束 ---------------



// ---------------- 处理消息列表功能开始 ----------------
const messageListRef = ref()
const domHeight = ref<number>(0)
const messageListHeight = ref<number>(0)

nextTick(()=>{
    domHeight.value = document.documentElement.clientHeight;
})

const loading = ref(false)

// 完成
const finished = ref(false)

// 消息列表参数
const messageListParams = reactive<MessageListParam>({
    from_uid: userStore.profile.user.uid,
    to_uid: route.query.to_uid as never,
    is_dialogue: 1,
    mode: route.query.mode as never,
    type: 1,
    page: 1,
    page_size: 10,
    sort_field: 'create_time',
    sort_type: 'desc',
    start_create_time: '',
    end_create_time: ''
})

// 消息列表
const messageList = ref<Message[]>([])

// 总条数
const total = ref<number>(0)

// 总页数
const totalPage = ref<number>(0)

// 获取消息列表
const getMessageList = async () => {
    if (finished.value == true) {
        return
    }

    const result = await reqMessageListAPI(messageListParams)
    messageList.value.push(...result.data.messages)
    total.value = result.data.total
    totalPage.value = result.data.total_page
    
    if (messageListParams.page < result.data.total_page) {
        messageListParams.page++
    } else {
        finished.value = true
    }
    await nextTick(()=>{
        // messageListHeight.value = messageListRef.value.clientHeight
    })
}
// ---------------- 处理消息列表功能结束 ----------------



// ------------------ 处理搜索功能开始 ------------------
// 搜索关键字
const handleSearch = () => {
}

// 处理图片预览
const handleShowImagePreview = (image_url: string) => {
    showImagePreview({images: [image_url], closeable: true});
}
// ------------------ 处理搜索功能结束 ------------------



// ----------------- 加载更多功能开始 -----------------
const onLoadMore = async () => {
    console.log('------------- 执行了加载更多 -------------');
    
    // 当挂载时显示骨架屏
    // if (isMounted.value) {
    //     isShowSkeleton.value = true
    // }
	await getMessageList()
    // isMounted.value = false
    // isShowSkeleton.value = false
}
// ----------------- 加载更多功能结束 -----------------
</script>

<style scoped lang="scss">
page,
.container {
    height: 100vh;
    // 过滤区域开始
    .filter-wrap {
        position: fixed;
        top: 45px;
        left: 0;
        width: 100%;
        z-index: 100;
        .date-filter-btn-box {
            display: flex;
            justify-content: flex-end;
            margin: 10px 0;
            padding-top: 10px;
            border-top: 1px solid #acabab;
            padding-right: 20px;
        }
    }
    // 过滤区域结束

    // 列表区域开始
    .content-wrap {
        padding-top: 100px;
        .list-wrap {
            height: calc(100vh - 100px);
            background-color: orange;
            padding: 0 10px;
            overflow: hidden;
            .record-item {
                background-color: #fff;
                padding: 15px;
                border-radius: 10px;
                margin-top: 5px;
                .title-box {
                    display: flex;
                    align-items: center;
                    padding-bottom: 6px;
                    border-bottom: 1px solid #f1f1f1;
                    .username {
                        font-size: 14px;
                        color: #acabab;
                        margin-left: 5px;
                    }
                }
                .content {
                    line-height: 22px;
                    font-size: 16px;
                    padding-top: 6px;
                    .text {
                        
                    }
                    .image {
                        width: 85px;
                        height: 85px;
                        border: 1px solid #efeeee;
                        display: flex;
                        align-content: center;
                        justify-content: center;
                        border-radius: 5px;
                        overflow: hidden;
                    }
                }
                .time {
                    display: flex;
                    justify-content: flex-end;
                    padding-top: 10px;
                    font-size: 14px;
                    color: #acabab;
                }
            }
        }
    }
}
</style>